import os
import uuid
from flask import Flask,render_template,Markup,flash,redirect,url_for,request,session,send_from_directory,Blueprint,current_app
from flask_sqlalchemy import SQLAlchemy
from imdb.forms.login import LoginForm
from imdb.forms.upload import UploadForm
from imdb.forms.article import ArticleForm
from models import Comment

imdb_app = Blueprint("imdb",__name__,template_folder=r"D:\Study\python_study\flask\imdb\template",
                     static_folder=r"D:\Study\python_study\flask\imdb\static")
user = {
    "username":"caoyx"
}

movies = [
    {"name":"大决战","year":"2020"},
    {"name":"地道战","year":"1999"},
    {"name":"一路往西","year":"2020"},
    {"name":"大秦帝国之纵横","year":"2015"},
    {"name":"我是外星人","year":"2020"},
    {"name":"西游外传","year":"2020"}
]
@imdb_app.route("/watch_list")
def watch_list():
    return render_template("watch_list.html",user=user,movies=movies)

@imdb_app.route("/index")
def index():
    return ""



@imdb_app.route("/banner")
def banner():
    return render_template("base.html")

@imdb_app.route("/sample")
def sample():
    return render_template("sample.html")

@imdb_app.route("/flash")
def toflash():
    flash("我是一个样例")
    return redirect(url_for("sample"))

@imdb_app.errorhandler(404)
def page_not_found(e):
    print(e.code,e.name,e.description)
    return render_template("errors/404.html",name=e.name,error=e.description),e.code

@imdb_app.route("/name_error")
def raise_name_error():
    raise NameError("名字错误")

@imdb_app.errorhandler(NameError)
def name_error(e):
    #print(e,dir(e))
    return render_template("errors/404.html", name=str(e), error="系统内部执行异常"), 500

@imdb_app.route("/user/register")
def register():
    return render_template("/user/register.html")

@imdb_app.route("/login",methods=["GET","POST"])
def login():
    fm = LoginForm()
    if fm.validate_on_submit():
    # validate_on_submit 等同于下面的判断
    #if request.method == "POST" and fm.validate():
        print("OK",request.data,request.args)
    else:
        return render_template("/user/login.html",form = fm)


def random_filename(filename):
    ext = os.path.splitext(filename)[1]
    return uuid.uuid4().hex+ext

@imdb_app.route("/photo",methods=["GET","POST"])
def photo():
    fm = UploadForm()
    if fm.validate_on_submit():
        # print("OK",request.files) #   ImmutableMultiDict([('photo', <FileStorage: 'set.png' ('image/png')>)])
        # print(request.files.get("photo"))  # 等同于 fm.photo.data
        print(fm.photo.data.name,fm.photo.data.filename)  # photo  set.png
        file = fm.photo.data
        #这里直接使用file.filename 不安全
        #filename = file.filename
        filename = random_filename(file.filename)
        file.save(os.path.join(imdb_app.config["UPLOAD_PATH"],filename))
        flash("文件保存成功")
        session['filenames'] = [filename]
        return redirect(url_for("imdb.show_images"))
    else:
        return render_template("/user/photo.html",form = fm)

@imdb_app.route("/uploads/<path:filename>")
def get_file(filename):
    return send_from_directory(imdb_app.config["UPLOAD_PATH"],filename)

@imdb_app.route("/show_images")
def show_images():
    return render_template("/user/show_images.html")

@imdb_app.route("/article",methods=["GET","POST"])
def article():
    """
    一个表单多个提交按钮，可以跟进提交按钮的data属性是否为True来判断 是哪个操作提交
    :return:
    """
    fm = ArticleForm()
    if fm.validate_on_submit():
        if fm.save.data:
            return "保存草稿"
        elif fm.publish.data:
            return "发布成功"
    else:
        return render_template("/article/article.html",form=fm)


@imdb_app.route("/comment/add")
def add_comment():
    pass

if __name__ == '__main__':
    imdb_app.run(debug=True)